<template>
  <use-page-header back />
  <div class="wrapper">
    <a-form layout="horizontal"
            :label-col="{ span: 2 }"
            :wrapper-col="{ span: 20 }"
            :model="form"
            ref="formRef"
            :rules="rules">
      <a-card>
        <a-tabs v-model:activeKey="tab"
                @tabChange="tabChange"
                size="large"
                type="card"
                :tabBarStyle="{ marginBottom: '24px' }">
          <a-tab-pane key="base"
                      tab="基本信息">
            <a-form-item label="标题"
                         help="请输入标题，50字符内"
                         name="title">
              <a-input show-count
                       :maxlength="120"
                       v-model:value="form.title"
                       name="title"
                       placeholder="请输入标题" />
            </a-form-item>
            <a-form-item label="分类"
                         help="请选择咖啡分类"
                         name="category">
              <a-cascader :options="options"
                          v-model:value="form.category"
                          style="width:600px"
                          @change="cascaderChange"
                          showSearch
                          :fieldNames="{ label: 'name', value: 'id', children: 'children' }">
              </a-cascader>
            </a-form-item>
            <a-form-item label="封面"
                         help="请上传封面图片,图片将会以1:1裁剪后上传，2M以内"
                         name="cover">
              <use-cover-upload v-model:value="form.cover" />
            </a-form-item>
            <a-form-item label="简介"
                         help="请输入简介，120个字以内，如果为空，默认提取详情前120个字符串">
              <a-textarea placeholder="请输入简介（选填）"
                          v-model:value="form.description"
                          show-count
                          :maxlength="120"></a-textarea>
            </a-form-item>
            <a-form-item label="详情"
                         name="content">
              <use-wang-editor height="500px"
                               v-model:value="form.content"
                               name="content" />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane tab="自定义字段"
                      key="fields">
            <!-- 自定义信息模板 调用组件 -->
            <keep-alive>
              <select-template v-model:value="form.custom_fields"
                               v-model:id="form.template" v-model:fields="form.template_fields" />
            </keep-alive>
          </a-tab-pane>
          <a-tab-pane tab="图集"
                      key="gallery">
            <a-form-item label="咖啡图集">
              <use-gallery-uploader v-model:value="form.gallery"
                                    :maxCount="20" />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="other"
                      tab="其他设置">
            <a-form-item label="是否推荐">
              <a-radio-group buttonStyle="solid"
                             v-model:value="form.recommend">
                <a-radio-button :value="1">是</a-radio-button>
                <a-radio-button :value="0">否</a-radio-button>
            </a-radio-group>
            </a-form-item>
            <a-form-item label="初始浏览数">
              <a-input-number v-model:value="form.views"
                              :min="0" />
            </a-form-item>
            <a-form-item label="初始点赞数">
              <a-input-number v-model:value="form.likes"
                              :min="0" />
            </a-form-item>
            <a-form-item label="允许访问">
              <a-radio-group buttonStyle="solid"
                             v-model:value="form.status">
                <a-radio-button :value="1">是</a-radio-button>
                <a-radio-button :value="0">否</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-card>
      <use-action-bar>
        <a-button>取消</a-button>
        <a-button type="primary"
                  :loading="state.loading"
                  @click="handleSubmit">保存修改</a-button>
      </use-action-bar>
    </a-form>
    <a-modal v-model:open="modalOpen"
              :bodyStyle="{padding:0}"
              :maskClosable="false"
              :closable="false"
              centered
             :footer="false">
      <a-result status="success"
                title="文章编辑成功"
                sub-title="返回列表 或是 继续发布 下一篇文章">
        <template #extra>
          <a-button key="console"type="primary" @click="$router.go(-1)">返回列表</a-button>
        </template>
      </a-result>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {
  UsePageHeader,
  UseWangEditor,
  UseActionBar,
  UseCoverUpload,
  UseGalleryUploader
} from '@/components';
import { onMounted, reactive, ref } from 'vue';
import SelectTemplate from './components/SelectTemplate.vue';
import useMessage from '@/hooks/useMessage';
import {type FormInstance } from 'ant-design-vue';
import { getCoffeeDetail, updateCoffee } from '@/server/modules/coffee';
import { getUserId, hasPermission } from '@/hooks';
import { useRoute} from 'vue-router';

// 当前选中tab
const tab = ref<string>('base');

//控制模态框显隐
const modalOpen = ref<boolean>(false);
/**
 *  
 * tab change 监听
 * */
const tabChange = (key: string) => {
  tab.value = key;
}
/**
 * 组件状态
 */
const state = reactive({
  loading: false
})
/**
 * 创建表单ref
 */
const formRef = ref<FormInstance>();
/**
 * 表单数据
 */
const form = reactive({
  id:0,
  title: '',
  content: '',
  user_id: getUserId(),
  category_id: 0,
  category: [] as string[],
  cover: '',
  description: '',
  custom_fields: [] as StateFieldsType[],
  template_fields:[],
  template: 0,
  gallery: [],
  views: 0,
  likes: 0,
  status: 1,
  recommend: 0
})
/**
 * 表单验证规则
 */
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 50, message: '内容不少于50个字符', trigger: 'blur' },
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'blur' },
  ],
  cover: [
    { required: true, message: '请上传封面图', trigger: 'blur' },
  ]
}
/**
 * 从缓存中读取分类列表
 */
const options = JSON.parse(localStorage.getItem('categoryList') || '[]')
/**
 * 分类选择 监听
 * @param value 
 */
const cascaderChange = (value: number[]) => {
  form.category_id = value.slice(-1)[0]
}
/**
 * 表单提交
 */
const handleSubmit = async () => {
  if(!hasPermission('delete')) return
  //校验字段模板中的字段
  if (form.custom_fields && form.custom_fields.length > 0) {
    const validateFields = form.custom_fields.filter(item => item.value == '' || item.value == null)
    if (validateFields.length > 0) {
      useMessage(0, '请填写 自定义字段 所有字段')
      return false
    }
  }
  try {
    state.loading = true
    await formRef.value?.validate()
    const res = await updateCoffee(form.id,form)
    if (res.code == 200) {
      setTimeout(() => {
        modalOpen.value= true
      }, 1000);
    }else{
      useMessage(res.code, res.message)
    }
  } catch (err: any) {
    useMessage(0, '请检查必填字段')
  } finally {
    setTimeout(() => {
      state.loading = false;
    }, 3000);
  }
}

const getDataDetail = async()=>{
  const id = useRoute().params.id || 0
  const res = await getCoffeeDetail(id as number)
  if(res.code === 200 && res.data){
    Object.assign(form, res.data)
  }
}
onMounted(()=>{
  getDataDetail()
})
</script>

<style scoped></style>